import { userCenterGetTokenInfo } from '../userCenter';
import { production } from '@src/util/onerror/index.js';
import { isDevelopment } from '@src/util/platform';
import { getRootWindow } from '@src/util/dom';
import { isEmpty } from '@src/util/type'

import { EventIdEnum, SecondEventIdEnum } from '@model/enum/TrackerEnum';

const rootWindow = getRootWindow(window);

interface formatParams {
  id: EventIdEnum;
  data?: any;
  secondId?: SecondEventIdEnum;
}

/**
 * @des 格式化埋点数据
 */
export const formatTrackerParams = (params: formatParams, win: any) => {
  let { id = '', data, secondId = '' } = params;
  if (!id) return null;
  if (!data) data = null;

  let payload = data;
  if (typeof data !== 'object') {
    payload = { defaultValue: data };
  }

  const currentTab = rootWindow.frameTabs && rootWindow.frameTabs.find((v:any) => v.show);
  let currentPageName = currentTab?.defaultTitle || currentTab?.originTitle;

  // 页面停留时间 当前页面为上一页
  if (id === 'PAGE_STAY_TIME') {
    currentPageName = data?.name || '';
  }

  // 新开标签页 当前页面为来源页
  if (id === 'OPEN_FRAME_TAB') {
    currentPageName = data?.from || '';
  }

  // 外层的菜单点击&导航栏点击事件
  const isOutFrameEvent = id.indexOf('MENU_') === 0 || id.indexOf('NAV_') === 0;
  if (isOutFrameEvent) {
    currentPageName = '首页';
  }

  return {
    terminal: 'PC',
    eventId: id,
    payload,
    secondEventId: secondId,
    currentPageName, // TODO 待优化
    type: 'click', // 目前默认click
  };
};

interface trackParams {
  terminal: 'PC' | 'MOBILE';
  eventId: string; // 事件ID
  payload?: string | object; // 事件数据
  secondEventId?: string; // 二级事件ID，统计一个或者多个eventId eg:详情页按钮的点击，包含详情页多个按钮
  currentPageName?: string; // 当前页面的名称，建议所有操作传此参数
}

/**
 * @des 上报点击埋点数据
 */
export const clickTracker = (params: trackParams) => {
  // 本地调试拿不到token
  const tokenInfo: any = userCenterGetTokenInfo();
  // console.log('tracker params', params, tokenInfo.token);
  rootWindow.publinkTracker?.clickStat(params, tokenInfo.token);
};

export const eventTrackURL = () => {
  const host = window.location.host;
  
  const appHosts = ['app.shb.ltd', 'shb3144.eapps.dingtalkcloud.com'];
  
  const isApp = appHosts.includes(host); // 钉钉端
  const isCloud = 'cloud.shb.ltd'.indexOf(host) > -1; // 独立端
  
  // 新域名
  const newDomains = ['https://cloud.servicemobile.net','https://shb3144.eapps.dingtalkcloud.com']

  const baseUrl = '/shb/metrics';
  const dev = 'https://slf-test.shb.ltd';
  const oldProd = isApp ? 'https://slf.shb.ltd' : isCloud ? 'https://slf.linker.ltd' : dev;
  const prod = newDomains.indexOf(location.origin) > -1 ? location.origin : oldProd

  let preUrl = '';
  if (production()) {
    preUrl = prod;
  } else {
    preUrl = isDevelopment() ? '/serve/eventTrack' : dev;
  }

  return `${preUrl}${baseUrl}`;
};
